import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class SensorSimulateFrame extends JFrame {
    private final JButton btn_login;
    private final JButton btn_clear;
    private final JTextField tf_username;
    private final JPasswordField tf_password;
    private final JTextField tf_url;
    private final JTextArea ta_log;
    private final JPanel contentPane;
    private final JLabel lbl_val;
    private String loginSta = "(未登录)";
    private String jSessionId;

    public SensorSimulateFrame() {
        setTitle("模拟1号传感器" + loginSta);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 800, 600);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        //upPane
        JPanel upPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        contentPane.add(upPane, BorderLayout.NORTH);

        JLabel lbl_url = new JLabel("连接URL：");
        tf_url = new JTextField("http://localhost/house");
        tf_url.setColumns(12);

        JLabel lbl_username = new JLabel("用户名：");
        tf_username = new JTextField("zhangsan");
        tf_username.setColumns(10);
        JLabel lbl_password = new JLabel("密码：");
        tf_password = new JPasswordField("zhangsan");
        tf_password.setColumns(10);

        btn_clear = new JButton("清除日志");
        btn_login = new JButton("登录");

        upPane.add(lbl_url);
        upPane.add(tf_url);
        upPane.add(lbl_username);
        upPane.add(tf_username);
        upPane.add(lbl_password);
        upPane.add(tf_password);
        upPane.add(btn_login);
        upPane.add(btn_clear);

        //centerPane
        ta_log = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(ta_log);
        contentPane.add(scrollPane, BorderLayout.CENTER);

        //downPane
        JLabel lbl_sensor = new JLabel("sen=");
        lbl_sensor.setFont(new Font("微软雅黑", Font.BOLD, 24));

        lbl_val = new JLabel("");
        lbl_val.setFont(new Font("微软雅黑", Font.BOLD, 24));

        JPanel downPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        contentPane.add(downPane, BorderLayout.SOUTH);
        downPane.add(lbl_sensor);
        downPane.add(lbl_val);


        addActions();
        setVisible(true);
        startSensor();
    }

    private void addActions() {
        //登录按钮事件
        btn_login.addActionListener(e -> {
            if (btn_login.getText().equals("登录")) {
                int code = login(tf_url.getText() + "/user/login", tf_username.getText(), new String(tf_password.getPassword()));
                if (code == 200) {
                    loginSta = "(已登录)";
                    btn_login.setText("退出登录");
                    setTitle("模拟1号传感器" + loginSta);
                    tf_username.setEnabled(false);
                    tf_password.setEnabled(false);
                }
            } else if (btn_login.getText().equals("退出登录")) {
                int code = clearLogin(tf_url.getText() + "/user/clearLogin");
                if (code == 200) {
                    loginSta = "(未登录)";
                    btn_login.setText("登录");
                    setTitle("模拟1号传感器" + loginSta);
                    tf_username.setEnabled(true);
                    tf_password.setEnabled(true);
                }
            }
        });
        //清除日志按钮事件
        btn_clear.addActionListener(e -> ta_log.setText(""));
    }

    private void startSensor() {
        HashMap<String, String> sensorParas = new HashMap<>();
        sensorParas.put("id", "1");
        sensorParas.put("value", "0.0");
        //sensorParas.put("relay", "off");
        Random r = new Random();
        Thread t = new Thread(() -> {
            while (true) {
                double val = 0.1 * (r.nextInt(1000));
                lbl_val.setText(String.format("%.2f", val));
                if (loginSta.equals("(已登录)")) {
                    sensorParas.put("value", lbl_val.getText());
                    int code = update(tf_url.getText() + "/sensor/updateSensor", sensorParas);
                    if (code != 200) {
                        System.out.println(code);
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }

    private int login(String url, String username, String password) {
        int responseCode = -1;
        HttpURLConnection connection = null;
        BufferedReader br = null;
        String result = null;//返回结果字符串
        try {
            URL urlobj = new URL(url);
            System.out.println(urlobj);
            // url远程连接
            connection = (HttpURLConnection) urlobj.openConnection();
            connection.setRequestMethod("POST");//请求方式
            connection.setConnectTimeout(15000);//设置连接主机服务器的超时时间：15000毫秒

            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            //请求参数
            connection.setDoOutput(true);
            String param = "username=" + username + "&password=" + password + "&relay=off";
            connection.getOutputStream().write(param.getBytes("UTF-8"));

            // 发送请求
            connection.connect();

            //响应头
            String setcookies = connection.getHeaderField("set-cookie");//JSESSIONID=F0F7531FE3B443C12D142082B500CF48; Path=/; HttpOnly
            System.out.println(setcookies);
            //获取JSESSIONID
            if (setcookies != null) {
                jSessionId = setcookies.substring(0, setcookies.indexOf(';'));
                System.out.println(jSessionId);
            }

            // 通过connection连接，获取输入流
            responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                InputStream is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    ta_log.append(temp);
                    ta_log.append("\r\n");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            ta_log.append(e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            ta_log.append(e.toString());
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }
        return responseCode;
    }


    private int update(String url, Map<String, String> parameters) {
        int responseCode = -1;
        HttpURLConnection connection = null;
        BufferedReader br = null;
        String result = null;//返回结果字符串
        try {
            //请求参数
            StringBuilder params = new StringBuilder();
            params.append("?");
            for (String p : parameters.keySet()) {
                params.append(p + "=" + parameters.get(p) + "&");
            }
            params.deleteCharAt(params.length() - 1);

            URL urlobj = new URL(url + params.toString());
            //System.out.println(urlobj);
            // url远程连接
            connection = (HttpURLConnection) urlobj.openConnection();
            connection.setRequestMethod("GET");//请求方式
            connection.setConnectTimeout(15000);//设置连接主机服务器的超时时间：15000毫秒
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);

            //设置cookie jsessionid
            if (jSessionId != null) {
                connection.addRequestProperty("Cookie", jSessionId);
            }
            // 发送请求
            connection.connect();

            // 通过connection连接，获取输入流
            responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                InputStream is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    ta_log.append(temp);
                    ta_log.append("\r\n");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            ta_log.append(e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            ta_log.append(e.toString());
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }
        return responseCode;
    }

    private int clearLogin(String url) {
        int responseCode = -1;
        HttpURLConnection connection = null;
        BufferedReader br = null;
        String result = null;//返回结果字符串
        try {
            URL urlobj = new URL(url);
            // url远程连接
            connection = (HttpURLConnection) urlobj.openConnection();
            connection.setRequestMethod("GET");//请求方式
            connection.setConnectTimeout(15000);//设置连接主机服务器的超时时间：15000毫秒
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);

            //设置cookie jsessionid
//            if (jSessionId != null) {
//                connection.addRequestProperty("Cookie", jSessionId);
//            }
            // 发送请求
            connection.connect();

            // 通过connection连接，获取输入流
            responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                InputStream is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    ta_log.append(temp);
                    ta_log.append("\r\n");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            ta_log.append(e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            ta_log.append(e.toString());
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }
        return responseCode;
    }

    public static void main(String[] args) {
        new SensorSimulateFrame();
    }
}
